package com.pmcc.cj.service;

import com.pmcc.utils.DateUtil;
import com.pmcc.utils.ResultBean;
import com.pmcc.utils.UUIDGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by tomas on 2020/10/3.
 */
@Transactional
@Service
public class FileService {
    @Value("${web.downloadFile}")
    private  String downloadFile;

    public ResultBean uploadFile(MultipartFile[] files){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<String> list = new ArrayList<>();
            if(files != null && files.length>0){
                for (MultipartFile file: files){
                    list.add(this.saveFile(file));
                }
            }
            resultBean.setRows(list);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    //保存文件，返回路径
    public String saveFile(MultipartFile file) throws Exception{
        String str=null;
        if(file!=null) {
            // 上传的文件存放路径
            String uploadDiskPath = downloadFile;
            String originalFilename = new String(file.getOriginalFilename());
            String[] arr = originalFilename.split("\\.");
            // 文件类型
            String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
            // 存放在服务器端的文件名
            String serverFileName = fileType == "" ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
            // 创建文件夹  年-月-日/goods
            String folder ="/" + DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
            // 数据库存放路径：年-月-日/文件名
            String fileUrl = folder + "/" + serverFileName;
            File targetFile = new File(uploadDiskPath, fileUrl);
            if (!targetFile.exists()) {
                targetFile.getParentFile().mkdirs();
                targetFile.createNewFile();
            }
            file.transferTo(targetFile);
            return fileUrl;
        }
        return str;
    }
}
